<template>
  <div>
    <!-- 输入框 -->
    <el-input
      v-model="input"
      clearable
      style="width: 200px; padding-left: 5px; padding-top: 10px"
      size="medium"
      placeholder="请输入内容"
    />

    <!-- 两个按钮 -->
    <el-button
      type="primary"
      size="medium"
      style="margin-left: 10px"
      icon="el-icon-search"
      @click="findByID()"
      v-hasBtn="'role_search'"
      >查找
    </el-button>
    <el-button
      type="primary"
      size="medium"
      style="margin-left: 10px"
      icon="el-icon-edit"
      @click="dialogTableVisible = true"
      v-hasBtn="'role_add'"
      >添加</el-button
    >

    <el-table
      :data="tableData"
      border
      :default-sort="{ prop: 'date', order: 'descending' }"
      :header-cell-style="{ 'text-align': 'center', 'font-size': '12px' }"
      :cell-style="{ 'text-align': 'center' }"
      style="width: 100%; margin-top: 10px"
    >
      <el-table-column label="角色名称" sortable>
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="说明">
        <template slot-scope="scope">
          <div slot="reference" class="name-wrapper">
            <span size="medium">{{ scope.row.remark }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="编辑状态" prop="modifiable">
        <template slot-scope="scope">
          <span v-if="scope.row.modifiable == true">可编辑</span>
          <span v-else>不可编辑</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.modifiable == true"
            size="mini"
            type="primary"
            @click="handleEdit(scope.row)"
            v-hasBtn="'role_edit'"
            >编辑
          </el-button>
          <el-button size="mini" v-if="scope.row.modifiable == true" type="danger" @click="handleDelete(scope.row)"  v-hasBtn="'role_delete'"
            >删除</el-button
          >
          <el-button size="mini" v-hasBtn="'role_pass'" v-if="scope.row.modifiable == true" type="primary" @click="handleAuthorization(scope.row)">授权</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- <el-pagination
      background
      style="margin-top: 10px"
      :page-sizes="[100, 200, 300, 400]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="400"
    /> -->
    <!--  -->
    
    <el-dialog title="权限配置" :visible.sync="openRole" @close="closeTree()">
        <el-tree :data="roleTable" show-checkbox  node-key="appId" ref="tree" :props="defaultProps" :default-checked-keys="rolebody.opIds" @node-click="handleNodeClick">
           
        </el-tree>

        <span slot="footer" class="dialog-footer">
          <el-button @click="openRole = false">取 消</el-button>
          <el-button type="primary" @click="submitTree()">确 定</el-button>
        </span>
    </el-dialog>


    <el-dialog
      title="创建"
      :visible.sync="dialogTableVisible"
      @close="resetForm('form')"
    >
      <el-form
        ref="form"
        label-position="left"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" clearable style="width: 350px" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色类型" prop="roleType">
          <el-select v-model="form.roleType" clearable placeholder="请输入角色类型">
            <el-option
              v-for="item in options"
              :key="item.dataValue"
              :label="item.dataName"
              :value="item.dataValue"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="角色说明" prop="remark">
          <el-input v-model="form.remark" clearable style="width: 350px" placeholder="请输入角色说明" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="编辑"
      :visible.sync="dialogTable"
      :destroy-on-close="true"
      @close="resetForm('form')"
    >
      <el-form
        ref="form"
        label-position="left"
        :rules="rules"
        :model="form"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" clearable style="width: 350px" placeholder="请输入角色名称"/>
        </el-form-item>
        <el-form-item label="角色类型" prop="roleType">
          <el-select v-model="form.roleType" clearable placeholder="请输入角色类型">
            <el-option
              v-for="item in options"
              :key="item.dataValue"
              :label="item.dataName"
              :value="item.dataValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色说明" prop="remark">
          <el-input v-model="form.remark" clearable style="width: 350px" placeholder="请输入角色说明"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogTable = false">取 消</el-button>
        <el-button type="primary" @click="update()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { createRole, editRole, getRoleID } from "@/api/role";
import { getRoleType } from "@/api/system";

export default {
  data() {
    return {
      defaultProps:{
          children: 'children',
          label: 'voName'
      },
      rolebody:{
        opIds:[],
        roleId: '',
      },
      roleTable:[{}],
      openRole:false,
      options: [{}],
      currentPage4: "",
      input: "",
      Id: "",
      form: {
        modifiable: true,
        roleName: "",
        remark: "",
        roleType: "",
      },
      rules: {
        roleName: [
          {
            required: true,
            message: "角色名称不能为空",
          },
        ],
        remark: [
          {
            required: true,
            message: "角色说明不能为空",
          },
        ],
        roleType: [
          {
            required: true,
            message: "角色类型不能为空",
          },
        ],
      },
      dialogTable: false,
      dialogTableVisible: false,
      tableData: [],
    };
  },
  created() {
    this.getList();
    this.getType();
    // this.getOpMenu();
  },
  methods: {
    getList() {
      this.$request({
        url: "/system/role/getAllRoles",
        method: "get",
      }).then((res) => {
        if (res.success) {
          this.tableData = res.data;
        }
      });
    },

    submitTree(){
      let res = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys())
      console.log(res)
      var arr = []
      for (var k = 0 ; k < res.length ; k ++){
         if (res[k] > 10000){
            arr.push(res[k])
         }
      }
      this.rolebody.opIds = arr
      console.log(this.rolebody.opIds, "this.rolebody.opIds")
      console.log(this.rolebody.roleId)

      this.$request({
        url: '/system/role/setOperation',
        method: 'post',
        data: this.rolebody
      }).then(res => {
        if (res.success){
          this.$notify.success('成功')
        } else {
          this.$notify.warning(res.errMessage)
        }
      })
    
      this.openRole = false

    },




    // getOpMenu() {
    //   this.$request({
    //     url: "/system/getOpMenu",
    //     method: "get",
    //   }).then(res => {
    //     console.log(res)
    //     if (res.success){
    //         for (var i = 0 ; i < res.data.length ; i ++){
    //             res.data[i].appId = i
    //         }
    //         this.roleTable = res.data
    //         console.log(this.roleTable)
    //     }
    //   });
    // },


   

    addRole() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          createRole(this.form)
            .then((res) => {
              if (res.success){
                this.dialogTableVisible = false;
                this.resetForm("form");
                this.getList();
              } else {
                this.$refs.warning(res.errMessage)
              }
             
            })
          .catch((error) => {
             console.log(error);
          });
        }
      })
    },
    findByID() {
      const that = this;
      if (this.input != "") {
        getRoleID(this.input).then((res) => {
          if (res.success){
            var array = [];
            array.push(res.data);
            this.tableData = array;
          } else {
                this.$refs.warning(res.errMessage)
              }
        });
      } else {
        this.getList();
      }
    },

    handleNodeClick(){

    },


    closeTree(){
      
    },


    getType() {
      getRoleType()
        .then((res) => {
          this.options = res.data;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    resetForm(formName) {
      this.form.roleName = "";
      this.form.remark = "";
      this.form.roleType = "";
      this.$refs[formName].clearValidate();
    },

    handleEdit(row) {
      this.form.roleName = row.roleName;
      this.form.remark = row.remark;
      this.form.roleType = row.roleType;
      this.Id = row.id;
      this.dialogTable = true;
    },

    update() {
      const that = this;
      var obj = {};
      obj.id = this.Id;
      obj.modifiable = true;
      obj.roleName = this.form.roleName;
      obj.roleType = this.form.roleType;

      editRole(obj)
        .then((res) => {
          if (res.success){
            this.dialogTable = false;
            this.resetForm("form");
            this.getList();
          }
        
        })
        .catch((error) => {
          console.log(error);
        });
    },

    handleAuthorization(val){
        this.rolebody.roleId = val.id
        this.$request({
          url: '/system/getRoleOperation/' + val.id,
          method: 'get'
        }).then(res => {
            if (res.success){
              var arr = []
              res.data.forEach(fir => {
                fir.children.forEach(sec => {

                    if (sec.state === 2){
                      console.log(sec.appId)    
                      arr.push(sec.appId)
                    }

                    if (sec.children !== null){
                      sec.children.forEach(th => {
                        console.log(th)
                        if (th.state === 2){
                          arr.push(th.appId)
                        }
                      })
                    }
                })
              })

              console.log(arr)

              this.rolebody.opIds = arr



              for (var i = 0 ; i < res.data.length ; i ++){
                  res.data[i].appId = i
              }
              this.roleTable = res.data
            }
          
        })
        console.log(this.rolebody.opIds)
        this.openRole = true
    },

    handleDelete(row) {
      console.log(row.id, "cdhjkshcksdhcksjd");
      this.$confirm(
        "此操作将永远删除角色---" + row.roleName + "---,是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        this.$request({
          url: "/system/role/delete/" + row.id,
          method: "get",
        }).then((res) => {
          console.log(res);
          if (res.success) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getRole();
          }
        });
      });
    },
  },
};
</script>
<style></style>
